<template>
  <div class="app-container">
    <div class="filter-container">
      <el-row :gutter="10">
        <el-col :xs="24" :sm="24" :md="12" :lg="16" :xl="16">
          <el-input  class="filter-item" clearable v-model="listQuery[0].value" placeholder="角色名称"  @keyup.enter.native="fetchListData" />
          <el-date-picker  class="filter-item-time" clearable  v-model="listQuery[2].value" format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss" @change="fetchListData" type="daterange" range-separator="-" start-placeholder="创建开始日期" end-placeholder="创建结束日期"></el-date-picker>
        </el-col>
        <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8" style="text-align: right">
          <el-button  class="filter-button" v-waves icon="el-icon-back" @click="$router.back()">返回</el-button>
          <el-button  class="filter-button" v-waves type="primary" icon="el-icon-search" @click="fetchListData">搜索</el-button>
          <el-button  class="filter-button" v-waves type="primary" icon="el-icon-edit" v-permission="['sysRole:add']" @click="handleCreateSysRole">新建</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="table-container">
      <base-list ref="table" url="/security/sysRole" :query="listQuery" :columns="columns" :format="format">
        <template slot="status" slot-scope="scope">
          <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
          <el-tag v-if="scope.row.status === 2" type="warning">禁用</el-tag>
        </template>
        <template slot="actions" slot-scope="scope">
          <el-button  v-waves v-permission="['security:sysRole:edit']" type="primary" @click="handleEditSysRole(scope.$index, scope.row)">编辑</el-button>
          <el-button  v-waves v-if="scope.row.status === 1" v-permission="['security:sysRole:disable']" type="warning" @click="handleStatusSysRole(scope.row.id, 2)">禁用</el-button>
          <el-button  v-waves v-if="scope.row.status === 2" v-permission="['security:sysRole:enable']" type="success" @click="handleStatusSysRole(scope.row.id, 1)">启用</el-button>
          <el-button  v-waves v-permission="['security:sysRole:delete']" type="danger" @click="handleDeleteSysRole(scope.$index, scope.row)">删除</el-button>
        </template>
      </base-list>
      <el-dialog :title="dialogTextMap[dialogStatus]" :visible.sync="createDialogVisible" :width="$store.state.app.device === 'mobile' ? '100%' : '60%'">
        <el-form ref="dataForm" :rules="rules" :model="temp" label-width="100px" label-suffix=": " :inline="true">
          <el-form-item label="角色名称" prop="authority">
            <el-input  class="form-item" v-model="temp.authority" placeholder="角色名称"></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select  class="form-item" v-model="temp.status" placeholder="状态">
              <el-option v-for="item in statusOptions" :key="item.id" :label="item.value" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button  type="primary" @click="handleSetRolePermission()">配置权限</el-button>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button  v-waves @click="createDialogVisible = false">取消</el-button>
          <el-button  v-waves type="primary" v-permission="['security:sysRole:add' || 'security:sysRole:edit ']" @click="dialogStatus==='create'?handleAddSysRole():handleUpdateSysRole()">提交</el-button>
        </div>
      </el-dialog>
      <el-dialog width="39%" title="权限设置" :visible.sync="permissionDialogVisible" append-to-body>
        <el-tree ref="permissionTable" accordion :data="permissionTree" show-checkbox  node-key="id" :props="defaultProps" :check-strictly="dialogStatus !== 'create'">
        </el-tree>
        <div slot="footer" class="dialog-footer">
          <el-button  @click="permissionDialogVisible = false">取消</el-button>
          <el-button  type="primary" @click="getRolePermissionIds()">确定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import permission from '@/directive/permission/index.js' // 权限判断指令
import waves from '@/directive/waves' // waves directive
import { create as createSysRole,
  update as updateSysRole,
  deleteById as deleteSysRole,
  updateSate as setSysRoleState,
  } from '@/api/security/sysRole'
import { getList as getPermissionList } from '@/api/security/sysPermission'
import { mapGetters } from 'vuex'
import BaseList from '@/components/BaseList'
export default {
  name: 'SysRole',
  components: { BaseList },
  directives: { permission, waves },
  data() {
    return {
      list: null,
      defaultProps: {
        children: 'children',
        label: 'authorityName'
      },
      columns: [
        { key: 'index', label: '编号', width: 40, fixed: 'left' },
        { key: 'authority', label: '角色名称' },
        { key: 'status', label: '状态', sortable: true  , type:'status' },
        { key: 'createTime', label: '创建时间',sortable: true },
        { key: 'updateTime', label: '修改时间',sortable: true },
        { key: 'actions', label: '操作', width: 220, fixed: 'right', align: 'left' }
      ],
      format: {
        index: (data, index) => { return index + 1 },
      },
      listQuery: [
        { column: "authority", condition: "like", value: null },
        { column: "status", condition: "=", value: null },
        { column: "createTime", condition: "bt", value: null }
      ],
      permissionTree:[],
      temp: {authority: undefined,status: undefined,permissionIds: []},
      statusOptions: [{ id: 1, value: '启用' }, { id: 2, value: '禁用' }],
      dialogTextMap: {update: '编辑',create: '新建', detail: '详情'},
      rules: {
        authority: [{ required: true, message: '角色名称必填!', trigger: 'blur' }],
        status: [{ required: true, message: '状态必填!', trigger: 'change' }],
      },
      dialogStatus: '',
      createDialogVisible: false,
      permissionDialogVisible:false
    }
  },
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  created() {
    const allOptions = JSON.parse(localStorage.getItem('allOptions'))

    this.handleGetPermission()
  },
  mounted() {
    this.fetchListData()
  },
  methods: {
    fetchListData() {
      this.$refs.table.fetchData(1)
    },
    reloadListData() {
      this.$refs.table.fetchData()
    },
    resetTemp() {
      this.temp = {authority: undefined,status: 1,permissionIds: []}
    },
    handleSetRolePermission() {
      this.permissionDialogVisible = true
      this.$nextTick(() => {
        this.$refs['permissionTable'].setCheckedKeys(this.temp.permissionIds);
      })
    },
    handleGetPermission() {
      getPermissionList().then(res => {
        this.permissionTree = res.data
      })
    },
    handleCreateSysRole() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.createDialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleEditSysRole(index, val) {
      this.temp = Object.assign({}, val)
      this.dialogStatus = 'update'
      this.createDialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleAddSysRole() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const queryData = Object.assign({}, this.temp)
          queryData.status = Number(queryData.status)
          createSysRole(queryData).then(() => {
            // this.list.unshift(queryData)
            this.fetchListData()
            this.createDialogVisible = false
            this.$notify.success('角色创建成功!')
          })
        }
      })
    },
    getRolePermissionIds() {
      this.temp.permissionIds = this.$refs.permissionTable.getCheckedNodes().map(e => e.id)
      this.permissionDialogVisible = false
    },
    handleUpdateSysRole() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp)
          updateSysRole(tempData).then(() => {
            this.reloadListData()
            this.createDialogVisible = false
            this.$notify.success('角色更新成功!')
          })
        }
      })
    },
    handleDeleteSysRole(index, val) {
      const self = this
      this.$confirm('确定要删除该角色？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteSysRole(val.id).then(() => {
          self.reloadListData()
          self.$notify.success('角色已删除!')
        })
      }).catch(() => {})
    },
    handleStatusSysRole(id, status) {
      const self = this
      this.$confirm('确定要'+['', '启用','禁用'][status]+'该角色？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        setSysRoleState(id, status).then(() => {
          self.createDialogVisible = false
          self.reloadListData()
          self.$notify.success('角色'+['', ' 已启用!', '已禁用!'][status])
        })
      }).catch(() => {return})
    }
  }
}
</script>

